import CryptoJS from "crypto-js"

type AesJsonObj = {
  ct: string,
  iv?: string,
  s?: string,
}

export const JsonFormatter = {
  stringify: function(cipherParams: CryptoJS.lib.CipherParams) {
    // create json object with ciphertext
    var jsonObj:AesJsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }
    // optionally add iv or salt
    if (cipherParams.iv) {
      console.log("civ", cipherParams.iv);
      jsonObj.iv = cipherParams.iv.toString();
    }
    if (cipherParams.salt) {
      console.log("cs", cipherParams.salt);
      jsonObj.s = cipherParams.salt.toString();
    }
    // stringify json object
    return JSON.stringify(jsonObj);
  },

  parse: function(jsonStr: string) {
    // parse json string
    var jsonObj = JSON.parse(jsonStr);
    // extract ciphertext from json object, and create cipher params object
    var cipherParams = CryptoJS.lib.CipherParams.create({
      ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
    });
    // optionally extract iv or salt
    if (jsonObj.iv) {
      cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
    }
    if (jsonObj.s) {
      cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
    }
    return cipherParams;
  }
};